package abacab.serialization.huffman;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;

/**
 * The context for decoding
 */
public class DecodingContext {
	/** The input stream */
	private final InputStream	inputStream;

	/** The currently written byte */
	private int								currentByte;

	/** The number of bits remaining before the current byte is completed */
	private int								bitsRemaining;

	/**
	 * Create the context
	 * 
	 * @param inputStream
	 *          the input stream
	 */
	public DecodingContext(InputStream inputStream) {
		this.inputStream = inputStream;
	}

	/**
	 * Check if the next bit in the stream is set
	 * 
	 * @return true if the next bit in the stream is set
	 * @throws IOException
	 *           if an error occurred while reading the stream
	 */
	public boolean isNextBitSet() throws IOException {
		if (this.bitsRemaining == 0) {
			this.currentByte = this.inputStream.read();
			if (this.currentByte < 0) {
				throw new EOFException();
			}
			this.bitsRemaining = 7;
		}
		else {
			this.bitsRemaining--;
		}
		return (this.currentByte & 1 << this.bitsRemaining) != 0;
	}
}